<template>
  <div>
    <el-container ref="addForm">
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="dataForm.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <EditorExtend
            ref="editor"
            @changeContentVal="changeContentVal()"
          ></EditorExtend>
        </el-form-item>

        <el-form-item label="标签" prop="labelIds">
          <el-select
            v-model="dataForm.labelIds"
            multiple
            placeholder="请选择"
            @change="labelListCheck"
          >
            <el-option
              v-for="item in labelList"
              :key="item.id"
              :label="item.labelName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="classificationId">
          <el-select v-model="dataForm.classificationId" placeholder="请选择">
            <el-option
              v-for="item in classificationList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否置顶" prop="whetherTop">
          <el-switch
            v-model="dataForm.whetherTop"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="beforeSubmit()"
            :disabled="submitDisable"
            >确定</el-button
          >
          <el-button @click="resetData()">重置</el-button>
          <el-button @click="test()">test</el-button>
        </el-form-item>
      </el-form>
    </el-container>
    <el-container ref="addSuccess">
      编辑成功
      <el-button type="primary" @click="changePageStyle">继续添加</el-button>
    </el-container>
  </div>
</template>

<script>
import Editor from "@/views/component/editor/editor";
import EditorExtend from "@/views/component/editor/editorExtend";
import { getCurrentTime } from "@/views/component/otherUtils/timeUtils";
import * as upload from "@/views/component/upload/policy";
import { uploadBuffer, downLoadBuffer } from "@/views/component/upload/oss";
export default {
  data() {
    return {
      labelList: [],
      classificationList: [],
      state: "",
      timeOutBool: false,
      submitDisable: false,
      visible: false,
      testVal: "",
      dataForm: {
        id: "",
        content: "",
        title: "",
        whetherTop: false,
        updateTime: "",
        labelIds: [],
        classificationId: ""
      },
      dataRule: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        classificationId: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        labelIds: [
          { required: true, message: "标签不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    $route(route) {
      if (route != undefined && route.name == "jiufen-blog-add-or-update") {
        this.initBefore();
      }
    }
  },
  components: {
    Editor,
    EditorExtend
  },
  mounted() {
    this.getLabelList();
    this.initBefore();
    this.getClassificationList();
  },
  methods: {
    //标签数量校验
    labelListCheck(newVal) {
      console.log("newVal:", newVal);
      let size = newVal.length;
      console.log("size:", size);
      if (size > 5) {
        this.dataForm.labelIds.pop();
        this.$message({
          message: "标签数量上限为4。",
          type: "warning"
        });
      }
    },

    //初始化前处理
    initBefore() {
      this.$refs.addSuccess.$el.style.display = "none";
      if (this.$route.params.id != undefined) {
        this.dataForm.id = this.$route.params.id;
        this.init(this.$route.params.id);
        this.state = "update";
      } else {
        this.state = "add";
      }
      // console.log(this.state);
    },

    //下载内容
    downloadContent(fileName) {
      downLoadBuffer(fileName).then(res => {
        this.dataForm.content = res;
        this.$refs.editor.content = this.dataForm.content;
      });
    },

    //使表单绑定的content与组件内容同步
    changeContentVal() {
      this.dataForm.content = this.$refs.editor.content;
    },

    //修改模式下的初始化
    init(id) {
      this.dataForm.id = id || 0;
      this.labelList = [];
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/blog/blogs/info/${this.dataForm.id}`),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            console.log("data:", data);
            if (data && data.code === 0) {
              this.dataForm.title = data.blogs.title;
              this.dataForm.whetherTop = data.blogs.whetherTop == 1;
              this.dataForm.updateTime = data.blogs.updateTime;
              this.dataForm.classificationId = data.blogs.classificationId;
              this.downloadContent(data.blogs.content);
              data.blogs.labelList.forEach(item => {
                this.dataForm.labelIds.push(item.id);
              });
            }
          });
        }
      });
    },

    //上传内容
    uploadContent(nowTime) {
      let fileId = upload.getRandId("content");
      upload.policy(fileId).then(res => {
        res.val = this.dataForm.content;
        uploadBuffer(res).then(resp => {
          this.dataFormSubmit(resp, nowTime);
        });
      });
    },

    //提交前处理
    beforeSubmit() {
      // debugger

      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          let nowTime = new Date().getTime();
          this.timeOutBool = true;
          this.submitDisable = true;
          this.uploadContent(nowTime);
        }
      });
      setTimeout(() => {
        this.submitFinish("超时");
      }, 5000);
    },

    // 表单提交
    dataFormSubmit(filePath, nowTime) {
      // debugger
      var labelArr = [];
      this.dataForm.labelIds.forEach(item => {
        let labelItem = {
          id: item
        };
        labelArr.push(labelItem);
      });
      this.$http({
        url: this.$http.adornUrl(
          `/blog/blogs/${!this.dataForm.id ? "save" : "update"}`
        ),
        method: "post",
        data: this.$http.adornData({
          id: this.dataForm.id,
          content: filePath,
          title: this.dataForm.title,
          likeCount: 0,
          whetherTop: this.dataForm.whetherTop ? 1 : 0,
          updateTime: nowTime,
          labelList: labelArr,
          classificationId: this.dataForm.classificationId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.visible = false;
              this.$emit("refreshDataList");
            }
          });
          this.changePageStyle();
          this.submitFinish(true);
          this.resetData();
        } else {
          this.$message.error(data.msg);
        }
        this.timeOutBool = false;
        this.submitFinish();
      });
    },

    //提交完成处理
    submitFinish(res) {
      if (this.timeOutBool) {
        if (res == "超时") {
          this.$message.error("响应超时");
        }
      }
      setTimeout(() => {
        this.submitDisable = false;
      }, 1000);
    },

    //初始化数据
    resetData() {
      this.dataForm = {
        id: "",
        content: "",
        title: "",
        whetherTop: false,
        updateTime: ""
      };
      this.$refs.editor.content = "";
    },

    //变更页面状态
    changePageStyle() {
      if (this.$refs.addSuccess.$el.style.display == "none") {
        this.$refs.addSuccess.$el.style.display = "";
        this.$refs.addForm.$el.style.display = "none";
      } else {
        this.$refs.addSuccess.$el.style.display = "none";
        this.$refs.addForm.$el.style.display = "";
      }
    },

    test() {
      console.log(this.dataForm);
      // this.getClassificationList();
    },

    //获取标签列表
    getLabelList() {
      this.$http({
        url: this.$http.adornUrl("/blog/label/list"),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.labelList = data.page.list;
        } else {
          this.labelList = [];
        }
        console.log("this.labelList:", this.labelList);
      });
    },

    //获取分类列表
    getClassificationList() {
      this.$http({
        url: this.$http.adornUrl("/blog/classification/list"),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.classificationList = data.page.list;
        } else {
          this.classificationList = [];
        }
        console.log("this.classificationList:", this.classificationList);
      });
    }
  }
};
</script>
